import { _decorator, Component, Node, EventTouch, Vec2, director, Vec3, input, Input, sys, Camera, Prefab, instantiate, Canvas, Size } from 'cc';
const { ccclass, property } = _decorator;
import { Msg } from "../../util/msg";

const MIN_SWIPE_DISTANCE = 50; // 最小滑动阈值
const SWIPE_EVENT_INTERVAL = 0.8; // 手势事件间隔时间

@ccclass('SwiperInput')
export class SwiperInput extends Component {

    private _swipeEventTime = 0;
    private _touchStartPosition: Vec2 = new Vec2();

    public onLoad() {
    }

    public onDestory() {
    }

    public onEnable() {
        input.on(Input.EventType.TOUCH_START, this._onTouchStart, this);
        input.on(Input.EventType.TOUCH_MOVE, this._onTouchMove, this);
        input.on(Input.EventType.TOUCH_END, this._onTouchEnd, this);
    }

    public onDisable() {
        input.off(Input.EventType.TOUCH_START, this._onTouchStart, this);
        input.off(Input.EventType.TOUCH_MOVE, this._onTouchMove, this);
        input.off(Input.EventType.TOUCH_END, this._onTouchEnd, this);
    }

    private _onTouchStart(e: EventTouch) {
        this._swipeEventTime = 0;
        this._touchStartPosition = e.getLocation();
    }

    private _onTouchMove(e: EventTouch) {
        const touchPosition = e.getLocation();
        const deltaX = touchPosition.x - this._touchStartPosition.x;
        const deltaY = touchPosition.y - this._touchStartPosition.y;
        const absDeltaX = Math.abs(deltaX);
        const absDeltaY = Math.abs(deltaY);

        if (absDeltaX < MIN_SWIPE_DISTANCE && absDeltaY < MIN_SWIPE_DISTANCE) {
            return;
        }

        if (absDeltaX > absDeltaY) {
            if (deltaX > 0) {
                this._triggerSwipeEvent('right');
            } else {
                this._triggerSwipeEvent('left');
            }
        } else {
            if (deltaY > 0) {
                this._triggerSwipeEvent('up');
            } else {
                this._triggerSwipeEvent('down');
            }
        }
    }

    private _onTouchEnd(e: EventTouch) {
        this._swipeEventTime = 0;
    }

    private _triggerSwipeEvent(direction: string) {
        const currentTime = Date.now() / 1000;
        if (currentTime - this._swipeEventTime >= SWIPE_EVENT_INTERVAL) {
            // console.log(`Swipe ${direction}`);
            this.node.emit(`input_swipe_${direction}`);
            this._swipeEventTime = currentTime;
        }
    }
}
